package com.inmaytide.website.controller.system;

import com.inmaytide.website.service.system.SysUserService;
import com.inmaytide.website.utils.CommonUtils;
import com.inmaytide.website.utils.configurations.SystemConstants;
import com.inmaytide.website.utils.log.annotation.LogInformation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;


@Controller
@RequestMapping("sys")
public class SystemController {

    @Resource
    private SysUserService userService;

    @LogInformation(description = "用户登录")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(UsernamePasswordToken token) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            CommonUtils.setSessionAttribute("error", CommonUtils.findLoginMessage(e));
            throw e;
        }
        return "redirect:index";
    }

    @RequestMapping("logout")
    public String logout(ModelMap model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (!ObjectUtils.isEmpty(currentUser)) {
            currentUser.logout();
            model.put("message", SystemConstants.LOGOUT_SUCCESS);
        }
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        Subject subject = SecurityUtils.getSubject();
        return subject.isAuthenticated() ? "redirect:index" : "login";
    }

    @RequestMapping("index")
    public String index() {
        return "index";
    }

    @RequestMapping("unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

}
